package server.autorization.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import controllers.Autoservice;
import autoservice.api.controller.IAutoservice;


@WebServlet("/SignInServlet")
public class SignInServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IAutoservice autoservice = Autoservice.getInstance();
	private static final String SUCCESSFUL_SIGN_iN =" , registration was successful";
	private static final String UNSUCCESSFUL_SIGN_iN = "An error has occurred. Perhaps this login already exists or login(password) is empty";
	private static final String LOGIN = "login";
	private static final String PASSWORD = "password";
	private static final String ANSWER = "answer";
	private static final String MAIN_PAGE = "/autorizationpages/MainPage.jsp";
	private static final String SIGN_IN_PAGE = "/autorizationpages/SignInPage.html";
	private static final String NAME = "name";
	private static final String SIGN_IN = "sign in";
	private static final String USER = "user";

       
    
    public SignInServlet() {
        super();
    }


	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter(LOGIN);
		String password = request.getParameter(PASSWORD);
		String name = request.getParameter(NAME);
		Boolean answer = autoservice.saveUser(login, password, name);
		
		if(answer){		
		request.setAttribute(ANSWER,name + SUCCESSFUL_SIGN_iN );
		request.getSession().setAttribute(USER, login);
		autoservice.setOperation(login, SIGN_IN);
		request.getRequestDispatcher(MAIN_PAGE).forward(request, response);
		}else{
			RequestDispatcher rd = getServletContext().getRequestDispatcher(SIGN_IN_PAGE);
			PrintWriter out= response.getWriter();
			out.println(UNSUCCESSFUL_SIGN_iN);
			rd.include(request, response);
		}
	}

}
